import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {NewPolicyDetailService} from './new-policy-detail.service';
import {NewPolicy, NewPolicyKeyWordList} from '../content/model/new-policy';
import _ from 'lodash';
import {RelatedPolicy} from '../content/model/related-policy';
import {timer} from 'rxjs';

@Component({
    selector: 'app-new-policy-detail',
    templateUrl: './new-policy-detail.component.html',
    styleUrls: ['./new-policy-detail.component.less']
})
export class NewPolicyDetailComponent implements OnInit {
    newPolicyDetail: NewPolicy = new NewPolicy();
    relatedPolicyDetail = '';
    relatedPolicy: RelatedPolicy = new RelatedPolicy();
    relatedPolicyDetailTemp = '';
    newPolicyDetailTemp = '';
    relatedPolicyId: number;
    relatedPolicyKeyword = [];
    keywordSimple = [];
    relatedPolicyList = [];
    isSpinning;
    relatedJudge;
    numberJudge;
    expandText = '展开';
    isExpand = null;

    fragment = '';  // 锚点, 传递的标引语句

    constructor(private route: ActivatedRoute,
                private newService: NewPolicyDetailService) {
    }

    ngOnInit(): void {
        this.route.fragment.subscribe(fragment => {
            //console.log('[fragment]', fragment)
            if(fragment){
                this.fragment = fragment;
                //this.fragment = decodeURIComponent(fragment);
            }
        });

        this.route.queryParams.pipe().subscribe((params: Params) => {
            if (params) {
                if (params.type) {
                    this.getRelatedPolicyDetail(params.id);
                    this.relatedJudge = true;
                } else {
                    this.getNewPolicyDetail(params.id);
                    this.relatedJudge = false;
                }
            }
        });
    }

    getNewPolicyDetail(id: number) {
        this.isSpinning = true;
        this.newService.getNewPolicyDetail(id).subscribe(res => {
            this.newPolicyDetail = res.result;
            this.keywordSimple = _.slice(this.newPolicyDetail.newPolicyKeywordList, 0, 20);
            this.isExpand = this.newPolicyDetail.newPolicyKeywordList.length <= 20;
            this.numberJudge = this.newPolicyDetail.number;
            this.newPolicyDetailTemp = this.newPolicyDetail.content;
            this.isSpinning = false;
        });
    }

// 相关政策详情
    getRelatedPolicyDetail(id: number) {
        this.isSpinning = true;
        this.newService.getRelatedPolicyDetail(id).subscribe(res => {
            if( !res['code'] || parseInt(res['code']) != 200 ){
                alert('当前政策不存在！');
            }else{
                this.relatedPolicy = res.result.policy;
                this.numberJudge = this.relatedPolicy.number;
                this.relatedPolicyDetail = res.result.policy.content;
                this.relatedPolicyDetailTemp = this.relatedPolicyDetail;
                this.relatedPolicyId = res.result.policy.id;
                this.relatedPolicyKeyword = res.result.keyword;
                if (this.relatedPolicyKeyword.length > 20) {
                    this.keywordSimple = _.slice(this.relatedPolicyKeyword, 0, 20);
                    this.isExpand = false;
                }else{
                    this.keywordSimple = this.relatedPolicyKeyword;
                }

                this.relatedPolicyList = res.result.relatedPolicy;
            }
            this.isSpinning = false;

                // 高亮 标引语句（从锚点带过来的）, 并自动滚到这里
            if( this.fragment ){
                this.heightLight( this.fragment );
            }
        });
    }

    // 高亮关键字, 并自动跳到第1个高亮处。
    heightLight(keyword: string) {
        console.log('[heightLight]', keyword);
        this.isSpinning = true;

        let canNotUseRe = /[%.]+/gi.test(keyword);       // 是否可以用正则来替换。用正则能替多个, 不用正则只能替一个。
        const re = new RegExp('' + keyword, 'gi');
        // 这个方法文本渲染过快，没有加载效果，为确保用户体验，设定一个延时器
        timer(100).subscribe(() => {
            if (this.relatedPolicyDetail) {
                if(canNotUseRe){
                    this.relatedPolicyDetail = this.relatedPolicyDetailTemp.replace( keyword, '<span class="heightLight">' + keyword + '</span>');
                }else{
                    this.relatedPolicyDetail = _.replace(this.relatedPolicyDetailTemp, re, '<span class="heightLight">' + keyword + '</span>');
                }
            } else {
                if(canNotUseRe){
                    this.newPolicyDetail.content = this.newPolicyDetailTemp.replace( keyword, '<span class="heightLight">' + keyword + '</span>');
                }else{
                    this.newPolicyDetail.content = _.replace(this.newPolicyDetailTemp, re, '<span class="heightLight">' + keyword + '</span>');
                }
            }
            this.isSpinning = false;
        });

        timer(100).subscribe(() => {
            try {   // 自动滚动到第1个高亮处。不能用id, id会直接被过滤掉。
                document.querySelector('.heightLight').scrollIntoView();
            } catch (e) { }
        });
    }

    // 展开/收起关键词列表
    expandList() {
        if (this.isExpand) {
            this.expandText = '展开';

        } else {
            this.expandText = '收起';

        }
        this.isExpand = !this.isExpand;

    }


}
